<template>
  <div class="chartbox" ref="chartRef"></div>
  <el-button type="primary" class="myBtn" @click="toQG" v-show="flag && userCode == 'root'"
    >全国</el-button
  >
</template>

<script setup>
import { ref, onMounted, onUnmounted, defineProps, defineEmits } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'

const store = useUserStore()
const userCode = store.userInfo.divisionCode

const chartRef = ref(null)
const flag = ref(false)
let myChart = null

const props = defineProps({
  data: {
    type: Array
  }
})
const emits = defineEmits(['updateScreenData'])

// 使用 watchEffect 替代 watch，自动追踪依赖变化并执行回调函数
watchEffect(() => {
  if (props.data) {
    initChart()
  }
})

const option = {
  tooltip: {
    trigger: 'item', // 触发类型：数据项图形触发
    formatter: function (e) {
      return `地点<br />  ${e.data.name}: ${e.data.value[2]}级`
    }
  },
  visualMap: {
    seriesIndex: 0,
    left: 'left', // 根据实际情况调整位置
    bottom: 'bottom', // 根据实际情况调整位置
    pieces: [
      {
        gte: 3.0,
        lte: 3.9,
        label: '3.0 - 3.9',
        symbol: 'circle',
        symbolSize: [8, 8],
        itemStyle: { color: '#91cc75', borderColor: '#FFFFFF', borderWidth: 1 }
      },
      {
        gte: 4.0,
        lte: 4.9,
        label: '4.0 - 4.9',
        symbol: 'circle',
        symbolSize: [12, 12],
        itemStyle: { color: '#fac858', borderColor: '#FFFFFF', borderWidth: 1 }
      },
      {
        gte: 5,
        label: '5.0+',
        symbol: 'circle',
        symbolSize: [16, 16],
        itemStyle: { color: '#ff2f14', borderColor: '#FFFFFF', borderWidth: 0 }
      }
    ],
    inRange: {
      color: ['#91cc75', '#fac858', '#ff2f14']
    }
  },
  geo: {
    map: 'china', // 使用的地图类型
    roam: true, // 是否允许缩放和平移
    // label: {
    //   emphasis: {
    //     show: true,
    //     color: "#fff",
    //   },
    // },

    itemStyle: {
      normal: {
        borderColor: '#02AAF6', // 默认边界线颜色设置为透明
        borderWidth: 1, // 默认边界线宽度
        areaColor: '#fff'
      },

      emphasis: {
        // 鼠标悬停时的样式
        areaColor: '#0e9cff', // 悬停时区域填充颜色（这里设置为白色，实际可设为透明或其他颜色）
        borderColor: '#0e9cff', // 悬停时边界线颜色
        borderWidth: 2 // 悬停时边界线宽度
      }
    }
  },
  series: [
    {
      name: '地点',
      type: 'scatter', // 图表类型为效果散点图
      coordinateSystem: 'geo' // 使用地理坐标系
    }
  ]
}

const initData = (e) => {
  if (myChart) {
    myChart.dispose()
    myChart = null
  }
  myChart = echarts.init(chartRef.value)
  var data = props.data
  const sdata = []
  for (const item of data) {
    sdata.push({
      name: item.province,
      value: [item.longitude, item.dimensionality, item.shockLevel]
    })
  }
  option.series[0].data = sdata
  myChart.setOption(option)
  if (userCode != 'root') return
  myChart.on('click', function (params) {
    let name = params.name
    if (params.componentType === 'geo') {
      emits('updateScreenData', name)
      flag.value = true
    }
  })
}

const toQG = () => {
  emits('updateScreenData', '')
  flag.value = false
}

let chartFlag = false
// 初始化图表 加载地图 json
const initChart = () => {
  if (chartFlag) {
    initData()
    return
  }

  var user = userCode == 'root' ? 'china' : userCode
  fetch(`/static/map-geojson/${userCode == 'root' ? 'china' : userCode}.json`)
    .then((e) => {
      return e.json()
    })
    .then((e) => {
      console.log(e)

      echarts.registerMap(userCode, e)
      option.geo.map = userCode
      chartFlag = true
      initData()
    })
}

// 组件挂载后初始化图表
onMounted(() => {
  window.addEventListener('resize', () => {
    myChart && myChart.resize()
  })
})

// 组件卸载时销毁图表实例，避免内存泄漏
onUnmounted(() => {
  if (myChart) {
    myChart.dispose()
  }
})
</script>

<style lang="scss" scoped>
.chartbox {
  width: 100%;
  height: 400px;
}
.myBtn {
  position: absolute;
  right: 20px;
  bottom: 20px;
}
</style>